<script setup lang="ts">
import {
  ref,
  watch,
  defineEmits,
  computed,
  onMounted,
  watchEffect,
  type ComputedRef,
  nextTick,
} from 'vue'
import { Marked } from 'marked'
import axios from 'axios'
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  type CarouselApi,
} from '@/components/ui/carousel'
import { useAssistantListStore } from '@/store/assistantListStore'
import type { AssistantProps, TableListType, Step } from '@/type'
import { isAndroid, isIos } from '@/config'
import double_left from '@/icon/double-left.svg'
import double_left_active from '@/icon/double-left-active.svg'
import 分享 from '@/icon/分享.svg'

const props = defineProps<{
  currentAssistantKey: string
  topicKey: string
  tableList: TableListType
}>()

const emit = defineEmits<{
  (event: 'stepChange', step: Step): void
}>()

const api = ref<CarouselApi>()

const currentIndex = ref<number>(0)

const platformList = computed(() => {
  return Object.keys(props.tableList)
})

const stepsList = computed(() => {
  return props.tableList[currentPlatform.value!] || []
})

const preferedPlatform = isIos() ? 'iOS' : isAndroid() ? 'Android' : 'PC'
const currentPlatform = ref<keyof TableListType>()
const store = useAssistantListStore()
const { updateCompletedAssistantList } = store

watchEffect(() => {
  if (props.currentAssistantKey == props.topicKey) {
    // currentPlatform.value = getDefaultAndSetPlatform()
    const article = stepsList.value[currentIndex.value]?.article
    if (article) {
      axios
        .get(article)
        .then(async (resp) => {
          const compiledMarkdown = await new Marked().parse(resp.data)
          emit('stepChange', {
            currentPlatform: currentPlatform.value!,
            platformList: platformList.value,
            content: compiledMarkdown,
          })
        })
        .catch((error) => {
          console.error('Error loading markdown file:', error)
        })
    }
  }
})

watch(
  () => props.currentAssistantKey,
  (newKey) => {
    currentPlatform.value = getDefaultAndSetPlatform()
    resetCarousel().then(trySyncRead)
  },
  { immediate: true },
)

function trySyncRead() {
  if (props.topicKey !== props.currentAssistantKey) return
  if (currentIndex.value == stepsList.value.length - 1) {
    updateCompletedAssistantList(props.topicKey)
  }
}

function getDefaultAndSetPlatform() {
  return props.tableList[preferedPlatform]
    ? preferedPlatform
    : (platformList.value[0] as keyof TableListType)
}

function changePlatform(plat: keyof TableListType) {
  currentPlatform.value = plat
  resetCarousel().then(trySyncRead)
}

function setApi(val: CarouselApi) {
  api.value = val
  val?.on('select', async () => {
    currentIndex.value = api.value?.selectedScrollSnap() as number
    trySyncRead()
  })
}

function handlePrev(): boolean {
  if (api.value?.canScrollPrev()) {
    api.value?.scrollPrev()
    return true
  }
  return false
}

function handleNext(): boolean {
  if (api.value?.canScrollNext()) {
    api.value?.scrollNext()
    return true
  }
  return false
}

defineExpose({
  handlePrev,
  handleNext,
  changePlatform,
})

async function resetCarousel() {
  return await nextTick(() => {
    if (api.value) {
      currentIndex.value = 0
      api.value.reInit()
      api.value.scrollTo(0)
    }
  })
}
</script>
<template>
  <div
    class="assistantDetailPC w-full h-full flex flex-col items-center justify-center"
  >
    <div
      class="flex-1 min-h-0 w-full max-w-[80vw] flex items-center justify-between relative"
    >
      <Carousel
        class="relative w-full h-full"
        ref="carousel_ref"
        @init-api="setApi"
      >
        <CarouselContent>
          <CarouselItem v-for="item in stepsList" :key="item.media">
            <div class="w-full h-full pic-wrap">
              <!-- put your custom content here -->
              <img
                class="h-full mx-auto object-contain select-none cursor-pointer pic"
                draggable="false"
                :src="item.media"
              />
            </div>
          </CarouselItem>
        </CarouselContent>
      </Carousel>
    </div>
  </div>
</template>
<style scoped lang="scss">
/* Hide scrollbar for Chrome, Safari and Opera */
.assistantDetailPC .scrollbar-hidden::-webkit-scrollbar {
  display: none;
}

/* .left {
  position: absolute;
  left: -36px;
  height: 100%;
  width: 36px;
  height: 100%;
  display: flex;
  align-items: center;

  &__button {
    background: #ffffff;
    border-radius: 8px;
    border: 1px solid #999;

    &:hover {
      cursor: pointer;
      background: rgba(46, 193, 204, 0.1);
      border-radius: 8px;
      border: 1px solid #30c1cc;
      transform: scale(1.05);
    }
  }
} */

/* .right {
  position: absolute;
  right: -36px;
  height: 100%;
  width: 36px;
  height: 100%;
  display: flex;
  align-items: center;

  &__button {
    background: #ffffff;
    border-radius: 8px;
    border: 1px solid #999;

    &:hover {
      cursor: pointer;
      background: rgba(46, 193, 204, 0.1);
      border-radius: 8px;
      border: 1px solid #30c1cc;
      transform: scale(1.05);
    }
  }
} */

/* Hide scrollbar for IE, Edge and Firefox */
.scrollbar-hidden {
  -ms-overflow-style: none; /* IE and Edge */
  scrollbar-width: none; /* Firefox */
}
.pic-wrap {
  padding: 10px;
}

.pic {
  filter: drop-shadow(1px 2px 4px hsl(0, 0%, 60.8%));
}
</style>
